package com.blog.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blog.entity.User;
import com.blog.service.UserService;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/users")
@CrossOrigin
public class UserController {

    private final UserService userService;
    private final PasswordEncoder passwordEncoder;

    public UserController(UserService userService, PasswordEncoder passwordEncoder) {
        this.userService = userService;
        this.passwordEncoder = passwordEncoder;
    }

    /**
     * 获取用户列表（仅管理员）
     */
    @GetMapping
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> getUserList(
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String keyword) {
        
        Page<User> page = new Page<>(current, size);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        
        if (keyword != null && !keyword.trim().isEmpty()) {
            queryWrapper.like("username", keyword)
                       .or()
                       .like("nickname", keyword);
        }
        
        queryWrapper.orderByDesc("create_time");
        
        IPage<User> userPage = userService.page(page, queryWrapper);
        
        return ResponseEntity.ok(userPage);
    }

    /**
     * 创建用户（仅管理员）
     */
    @PostMapping
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> createUser(@RequestBody User user) {
        try {
            // 检查用户名是否已存在
            if (userService.findByUsername(user.getUsername()) != null) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "用户名已存在");
                return ResponseEntity.badRequest().body(errorResponse);
            }
            
            // 加密密码
            user.setPassword(passwordEncoder.encode(user.getPassword()));
            
            boolean success = userService.save(user);
            if (success) {
                return ResponseEntity.ok(user);
            } else {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "保存用户失败");
                return ResponseEntity.badRequest().body(errorResponse);
            }
        } catch (Exception e) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", "创建用户失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }

    /**
     * 更新用户信息（仅管理员）
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> updateUser(@PathVariable Long id, @RequestBody User user) {
        try {
            User existingUser = userService.getById(id);
            if (existingUser == null) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "用户不存在");
                return ResponseEntity.badRequest().body(errorResponse);
            }
            
            // 更新用户信息（不更新密码和用户名）
            existingUser.setNickname(user.getNickname());
            existingUser.setEmail(user.getEmail());
            existingUser.setRole(user.getRole());
            existingUser.setStatus(user.getStatus());
            
            userService.updateById(existingUser);
            return ResponseEntity.ok(existingUser);
        } catch (Exception e) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", "更新用户失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }

    /**
     * 删除用户（仅管理员）
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> deleteUser(@PathVariable Long id) {
        try {
            User user = userService.getById(id);
            if (user == null) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "用户不存在");
                return ResponseEntity.badRequest().body(errorResponse);
            }
            
            // 不允许删除admin用户
            if ("admin".equals(user.getUsername())) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "不能删除管理员账户");
                return ResponseEntity.badRequest().body(errorResponse);
            }
            
            userService.removeById(id);
            Map<String, String> successResponse = new HashMap<>();
            successResponse.put("message", "删除成功");
            return ResponseEntity.ok(successResponse);
        } catch (Exception e) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", "删除用户失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }

    /**
     * 修改用户状态（仅管理员）
     */
    @PutMapping("/{id}/status")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> updateUserStatus(@PathVariable Long id, @RequestBody Map<String, Object> statusData) {
        try {
            User user = userService.getById(id);
            if (user == null) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "用户不存在");
                return ResponseEntity.badRequest().body(errorResponse);
            }
            
            // 不允许禁用admin用户
            if ("admin".equals(user.getUsername())) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "不能禁用管理员账户");
                return ResponseEntity.badRequest().body(errorResponse);
            }
            
            Integer status = (Integer) statusData.get("status");
            user.setStatus(status);
            userService.updateById(user);
            
            Map<String, String> successResponse = new HashMap<>();
            successResponse.put("message", "状态更新成功");
            return ResponseEntity.ok(successResponse);
        } catch (Exception e) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", "状态更新失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }

    /**
     * 重置用户密码（仅管理员）
     */
    @PutMapping("/{id}/password")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> resetPassword(@PathVariable Long id, @RequestBody Map<String, String> passwordData) {
        try {
            User user = userService.getById(id);
            if (user == null) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "用户不存在");
                return ResponseEntity.badRequest().body(errorResponse);
            }
            
            // 不允许重置admin用户密码
            if ("admin".equals(user.getUsername())) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "不能重置管理员密码");
                return ResponseEntity.badRequest().body(errorResponse);
            }
            
            String newPassword = passwordData.get("newPassword");
            user.setPassword(passwordEncoder.encode(newPassword));
            userService.updateById(user);
            
            Map<String, String> successResponse = new HashMap<>();
            successResponse.put("message", "密码重置成功");
            return ResponseEntity.ok(successResponse);
        } catch (Exception e) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", "密码重置失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }
}
